package com.netty.decoder.protocol;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

/**
 * @author xl-9527
 * @since 2025/8/9
 **/
public class RedisClient {

    /**
     * 换行
     */
    final static byte[] CRLF = new byte[]{13, 10};
    private static final Logger log = LoggerFactory.getLogger(RedisClient.class);

    public ChannelFuture connection() {
        final Bootstrap bootstrap = new Bootstrap()
                .channel(NioSocketChannel.class)
                .group(new NioEventLoopGroup(1))
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(final NioSocketChannel ch) throws Exception {
                        final ChannelPipeline pipeline = ch.pipeline();
                        // 日志
                        pipeline.addLast(new LoggingHandler());
                        // 解码
                        pipeline.addLast(new LineBasedFrameDecoder(1024));
                        // 自己的业务
                        pipeline.addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelActive(final ChannelHandlerContext ctx) throws Exception {
                                final ByteBuf buffer = ctx.alloc().buffer();
                                setComment(buffer, "username", "lisi");
                                ctx.writeAndFlush(buffer);
                                super.channelActive(ctx);
                                log.info("连接成功, 写入 redis");
                            }

                            @Override
                            public void channelRead(final ChannelHandlerContext ctx, final Object msg) throws Exception {
                                log.info("读到数据：{}", msg);
                                super.channelRead(ctx, msg);
                            }
                        });
                    }
                });
        return bootstrap.connect(new InetSocketAddress("127.0.0.1", 6379));
    }

    public void setComment(final ByteBuf buffer, final String key, final String value) {
        buffer.writeBytes("*3".getBytes()).writeBytes(CRLF);
        buffer.writeBytes("$3".getBytes()).writeBytes(CRLF);
        buffer.writeBytes("set".getBytes()).writeBytes(CRLF);
        buffer.writeBytes(("$" + key.length()).getBytes(StandardCharsets.UTF_8)).writeBytes(CRLF);
        buffer.writeBytes(key.getBytes()).writeBytes(CRLF);
        buffer.writeBytes(("$" + value.length()).getBytes()).writeBytes(CRLF);
        buffer.writeBytes(value.getBytes()).writeBytes(CRLF);
    }
}
